#include "TournamentSelectionStrategy.h"
#include "Chromosome.h"

TournamentSelectionStrategy::TournamentSelectionStrategy(int _tournamentSize) : SelectionStrategy(),
                    tournamentSize(_tournamentSize)
{
}

Chromosome* TournamentSelectionStrategy::selectOne(const QList<Chromosome*>& chromosomeList)
{
    TRACE_FUNC_ENTRY
    Chromosome* chromosome;

    //if tournament size not set or too big, choose 1/10 number of chromosomes
    if(tournamentSize == 0 || tournamentSize > chromosomeList.size())
    {
        qWarning("tournament size not set or wrong!");
        tournamentSize = chromosomeList.size()/10;
    }

    //qDebug() << "tournamentSize: " << tournamentSize;

    QList< Chromosome* > tmpList;

    for(int i=0;i<tournamentSize;++i)
    {
        int index = qrand() % chromosomeList.size();
        tmpList.append(chromosomeList[index]);
    }

    qSort(tmpList.begin(), tmpList.end(), Chromosome::greaterThan);

    //for(int i=0;i<tmpList.size();++i)
    //    qDebug() << i << ": " << tmpList[i].first << " " << tmpList[i].second;

    chromosome = tmpList.first();
    //qDebug() << *chromosome;

    TRACE_FUNC_EXIT
    return chromosome;
}

void TournamentSelectionStrategy::setSize(int _tournamentSize)
{
    if(_tournamentSize > 0)
        tournamentSize = _tournamentSize;
}
